package cn.common.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.util.Map;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.util.JRLoader;

/**
 * jasperreport工具类
 * 
 * @author 孙树林
 * 
 */
public class JasperreportsUtils {

	/**
	 * 生成docx文档
	 * 
	 * @param reportFile
	 * @param conn
	 * @throws JRException
	 * @throws IOException 
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static byte[] docx(String reportFile, Map parameter, Connection conn) throws JRException, IOException {
		// 载入报表文件
		JasperReport jasperReport = (JasperReport) JRLoader.loadObjectFromFile(reportFile);
		JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameter, conn);
		
		JRDocxExporter exporter = new JRDocxExporter();
		
		ByteArrayOutputStream is = new ByteArrayOutputStream();
		BufferedOutputStream bis = new BufferedOutputStream(is);
		
		// 设置导出docx参数
		exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
		exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, bis);
		exporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
		// 执行
		exporter.exportReport();
		byte bytes[] = is.toByteArray();
		bis.close();
		is.close();
		
		return bytes;
	}
}
